package com.dyz.leetcode;

import java.util.*;

public class LevelOrder102 {

    private List<List<Integer>> res = new ArrayList<>();
    private Stack<List<TreeNode>> stack = new Stack<List<TreeNode>>();
    //方法一使用栈
    public List<List<Integer>> levelOrder(TreeNode root) {
        //使用栈方法
        if(root==null){return res;}
        //初始化
        List<TreeNode> rootLevel = new ArrayList<>();
        rootLevel.add(root);
        stack.push(rootLevel);
        while (!stack.isEmpty()){
            List<TreeNode> currLevel = stack.pop();
            List<Integer> list = new ArrayList<>();
            List<TreeNode> nextLevel = new ArrayList<>();

            for(int i =0;i<currLevel.size();i++){
                TreeNode node = currLevel.get(i);
                list.add(node.val);
                if(node.left!=null){nextLevel.add(node.left);}
                if(node.right!=null){nextLevel.add(node.right);}
            }
            if(nextLevel.size()>0){stack.push(nextLevel);}
            res.add(list);
        }
        return res;
    }
    //使用队列
    public List<List<Integer>> levelOrder1(TreeNode root) {
        if(root==null){return res;}
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            List<Integer> list = new ArrayList<>();
            int currSize = queue.size();
            for(int i=0; i<currSize; i++){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left!=null){queue.add(node.left);}
                if(node.right!=null){queue.add(node.right);}
            }
            res.add(list);
        }
        return res;
    }
}
